package com.bsoft.gol.hcb.service.task;

import com.bsoft.gol.hcb.service.prescriptionCirculation.DrugOrdersService;
import ctd.job.annotation.ScheduleJob;
import ctd.job.pojo.JobParameter;
import com.bsoft.gol.hcb.dao.prescriptionCirculation.OdsOrderToPrescriptionDAO;
import com.bsoft.gol.hcb.dao.prescriptionCirculation.OdsPrescriptionOrderDAO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pcn.consultation.ConsultAsk;
import pcn.enums.FeeTypeEnum;
import pcn.prescribe.OdsOrderToPrescription;
import pcn.prescribe.OdsPrescriptionInfo;
import pcn.prescribe.OdsPrescriptionOrder;
import service.rpc.ConsultAskServiceIntf;
import service.rpc.PrescriptionInfoIntf;
import com.bsoft.gol.hcb.utils.CommonUtils;
import org.atag.util.common.RedisUtil;

import java.util.Date;
import java.util.List;

/**
 * @description: 在线咨询记录查询定时任务
 * @author: chenJij@bsoft.com.cn
 * @date: 2019/10/28 12:20
 */
@Component
public class ConsultTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConsultTask.class);
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ConsultAskServiceIntf consultAskServiceIntf;
    @Autowired
    private OdsPrescriptionOrderDAO odsPrescriptionOrderDAO;
    @Autowired
    private OdsOrderToPrescriptionDAO odsOrderToPrescriptionDAO;
    @Autowired
    private DrugOrdersService drugOrderService;
    @Autowired
    private PrescriptionInfoIntf prescriptionInfoIntf;


    /**
     * 异步定时任务 取消订单
     */
    @ScheduleJob(jobName = "cancelAcceptExpireDrugOrder", cron = "0 0/1 * * * ?", shardingTotalCount = 1,
            description = "复诊配药支付超时自动取消", overwrite = true)
    public void cancelAcceptExpireDrugOrder(JobParameter jobParameter) {
        //通过redis处理集群模式下，定时任务同时间只执行一次 默认3分钟内不重复执行
        String key = "ConsultTask.cancelAcceptExpireDrugOrder";
        if (redisUtil.setnx(key, "1", 180)) {
            LOGGER.info(key + "开始执行");
        } else {
            LOGGER.info(key + "其他节点已执行");
            return;
        }

        List<OdsPrescriptionOrder> odsPrescriptionOrders =
				odsPrescriptionOrderDAO.queryOdsPrescriptionOrdersByPayExpireTime(new Date());
        if (CommonUtils.isNotEmpty(odsPrescriptionOrders)) {
            for (OdsPrescriptionOrder odsPrescriptionOrder : odsPrescriptionOrders) {
                try {
                    /*去流转平台取消订单*/
                    if (StringUtils.isNotEmpty(odsPrescriptionOrder.getPlatformOrderId())) {
                        drugOrderService.cancelPrescriptionOrder(odsPrescriptionOrder.getPlatformOrderId(), odsPrescriptionOrder.getOrderId());
                    }
                    odsPrescriptionOrder.setPayStatus("2");//支付状态 0：待支付·    1：已支付    2：支付超时   3 已取消
                    odsPrescriptionOrderDAO.update(odsPrescriptionOrder);
                    List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(odsPrescriptionOrder.getOrderId());

                    if (CommonUtils.isNotEmpty(odsOrderToPrescriptions)) {
                        for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                            if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {

                                OdsPrescriptionInfo odsPrescriptionInfo = prescriptionInfoIntf.getOdsPrescriptionInfo(odsOrderToPrescription.getFeeCode());
                                if (null != odsPrescriptionInfo && odsPrescriptionInfo.getExpirationDate() != null && odsPrescriptionInfo.getExpirationDate().getTime() > System.currentTimeMillis()) {
                                    odsPrescriptionInfo.setOrderFlag("2");
                                    odsPrescriptionInfo.setPayStatus("0");
                                    prescriptionInfoIntf.updateOdsPrescriptionInfo(odsPrescriptionInfo);
                                    ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(odsOrderToPrescription.getConsultId());
                                    if(null != consultAsk){
                                        //修改问诊记录存在可下单处方
                                        consultAsk.setPrescriptionStatus(1);
                                        consultAskServiceIntf.updateConsultAsk(consultAsk);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LOGGER.info("支付超时自动取消失败，药品订单id=" + odsPrescriptionOrder.getOrderId());
                }
            }
        }
        redisUtil.delete(key);
    }
}
